﻿<div>
    <ul class="list-unstyled m-0">
        <li>
            <div class="color-picker-item">@HeaderText</div>
        </li>
        <li role="separator" class="color-picker-separator"></li>
        <li>
            <div class="color-picker-item color-picker-container">
                @foreach(var color in colors) {
                    <div class="color-picker-cell @CssClassSelectedCell(color)" style="background-color:@color" tabindex="0"
                        @onkeypress="(e) => HandleActionKeys(e.Code, () => ChangeColor(color))"
                        @onclick="() => ChangeColor(color)"></div>
                }
            </div>
        </li>
        <li role="separator" class="color-picker-separator"></li>
        <li>
            <div class="color-picker-item color-picker-item-reset" @onclick="ResetColor"
                @onkeypress="(e) => HandleActionKeys(e.Code, ResetColor)">
                <div class="color-picker-cell" tabindex="0"></div>
                <div tabindex="0">No color</div>
            </div>
        </li>
    </ul>
</div>

@code {
    static readonly string[] colors = new[] {
        "#000000",
        "#c0c0c0",
        "#808080",
        "#808000",
        "#800000",
        "#800080",
        "#008000",
        "#008080",
        "#000080",
        "#ff0000",
        "#0000ff",
        "#ff00ff",
        "#00ffff",
        "#00ff00",
        "#ffff00"
    };

    void ChangeColor(string color) {
        SelectedColor = color;
        ColorChanged.InvokeAsync(color);
    }

    void ResetColor() {
        SelectedColor = "unset";
        ColorChanged.InvokeAsync("unset");
    }

    void HandleActionKeys(string key, Action handler) {
        if (key == "Enter" || key == "Space")
            handler();
    }

    string CssClassSelectedCell(string color) =>
        color == SelectedColor ? "selected" : "";

    [Parameter] public string HeaderText { get; set; }
    [Parameter] public EventCallback<string> ColorChanged { get; set; }
    [Parameter] public string SelectedColor { get; set; }
}
